package com.xm.rsi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xm.rsi.common.ErrorCode;
import com.xm.rsi.constant.CommonConstant;
import com.xm.rsi.exception.BusinessException;
import com.xm.rsi.mapper.FileDataMapper;
import com.xm.rsi.model.dto.audit.AuditAddRequest;
import com.xm.rsi.model.dto.filedata.FileDataAddRequest;
import com.xm.rsi.model.dto.filedata.FileDataQueryRequest;
import com.xm.rsi.model.dto.filedata.FileDataUpdateRequest;
import com.xm.rsi.model.entity.Audit;
import com.xm.rsi.model.entity.FileData;
import com.xm.rsi.model.entity.User;
import com.xm.rsi.model.vo.FileDataCountVO;
import com.xm.rsi.model.vo.FileDataVO;
import com.xm.rsi.service.AuditService;
import com.xm.rsi.service.FileDataService;
import com.xm.rsi.service.UserService;
import com.xm.rsi.utils.EmailUtils;
import com.xm.rsi.utils.OssClient;
import com.xm.rsi.utils.SqlUtils;
import com.xm.rsi.utils.TifToJpg;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

import static com.xm.rsi.utils.FileReader.*;


/**
 * @author xmm
 * @description 针对表【file_data】的数据库操作Service实现
 * @createDate 2023-10-02 18:47:18
 */
@Service
public class FileDataServiceImpl extends ServiceImpl<FileDataMapper, FileData>
        implements FileDataService {

    @Resource
    private UserService userService;

    @Resource
    private AuditService auditService;

    @Resource
    private EmailUtils emailUtils;

    @Override
    public Long addOne(FileDataAddRequest fileDataAddRequest, InputStream fileInputStream, String fileName, HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        FileData fileData = new FileData();
        BeanUtils.copyProperties(fileDataAddRequest, fileData);
        fileData.setCreateUser(user.getId());
        if (userService.isRootAdmin(user) || userService.isAdmin(user)) {
            fileData.setFileDataState(0);
        }
        InputStream byteArrayInputStream;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fileInputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
            byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            fileInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        fileData.setJpgUrl(TifToJpg.getJpgUrl(byteArrayInputStream));
        if (!save(fileData)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        String path = fileData.getId() + "_" + user.getId() + "_" + fileData.getFileName() + "_" + fileName;
        try {
            fileData.setUrl(getUrl(fileInputStream, path));
        } catch (Exception e) {
            removeById(fileData.getId());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        }
        if (!updateById(fileData)) {
            delFile(path);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return fileData.getId();
    }

    @Override
    public Boolean updOne(FileDataUpdateRequest fileDataUpdateRequest, InputStream fileInputStream, String fileName, HttpServletRequest request) {
        FileData fileData = getById(fileDataUpdateRequest.getId());
        String url = fileData.getUrl();
        FileData newFileData = new FileData();
        BeanUtils.copyProperties(fileDataUpdateRequest, newFileData);
        User user = userService.getLoginUser(request);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        }
        if (fileInputStream != null) {
            InputStream byteArrayInputStream;
            try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fileInputStream.read(buffer)) > -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                byteArrayOutputStream.flush();
                byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                fileInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            } catch (Exception e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
            newFileData.setJpgUrl(TifToJpg.getJpgUrl(byteArrayInputStream));
            String path = fileData.getId() + "_" + user.getId() + "_" + fileData.getFileName() + "-" + fileName;
            try {
                newFileData.setUrl(getUrl(fileInputStream, path));
            } catch (Exception e) {
                removeById(newFileData.getId());
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
            }
            if (!url.equals(path))
                delFile(url);
        }

        if (userService.isRootAdmin(user) || userService.isAdmin(user)) {
            return updateById(newFileData);
        }
        Long userId = fileData.getCreateUser();
        if (!user.getId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "该文件不是你创建的，无权修改");
        }
        newFileData.setFileDataState(1);
        return updateById(newFileData);
    }

    @Override
    public FileDataVO getFileDataVO(FileData fileData) {
        FileDataVO fileDataVO = new FileDataVO();
        BeanUtils.copyProperties(fileData, fileDataVO);
        return fileDataVO;
    }

    @Override
    public List<FileDataVO> getFileDataVOList(List<FileData> fileDataList) {
        List<FileDataVO> fileDataVOList = new ArrayList<>();
        for (FileData fileData : fileDataList) {
            FileDataVO fileDataVO = new FileDataVO();
            BeanUtils.copyProperties(fileData, fileDataVO);
            fileDataVOList.add(fileDataVO);
        }
        return fileDataVOList;
    }

    @Override
    public List<FileData> uploadDirectory(File tempFile, Long userId) {
        try {

            List<FileData> fileDataList = new ArrayList<>();
            File[] files = tempFile.listFiles();
            if (files == null) {
                return fileDataList;
            }
            if (files.length == 1) {
                files = files[0].listFiles();
            }
            List<String> txt = new ArrayList<>();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().endsWith(".txt")) {
                        txt = readTxt(file);
                    }
                }
            }
            if (files != null) {
                for (File file : files) {
                    if (file.getName().endsWith(".txt")) {
                        continue;
                    }
                    String fileName = file.getName();
                    if (fileName.split("——").length < 3) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "影像文件夹命名错误");
                    }
                    String tifName = fileName.split("——")[0];
                    String camera = fileName.split("——")[1];
                    String grade = fileName.split("——")[2];

                    if (file.isDirectory()) {
                        File[] innerFiles = file.listFiles();
                        if (innerFiles == null) {
                            continue;
                        }
                        FileData fileData = new FileData();
                        fileData.setFileDataState(1);
                        int index = 0;
                        File tifFile = null;
                        for (File innerFile : innerFiles) {
                            String innerName = innerFile.getName();
                            if (innerName.endsWith("tif") || innerName.endsWith("tiff") || innerName.endsWith("TIF") || innerName.endsWith("TIFF")) {
                                if (index == 0) {
                                    tifFile = innerFile;
                                    index = 1;
                                    continue;
                                } else {
                                    upOne(fileData, innerFile, userId, tifName);
                                    break;
                                }
                            }
                            String info;
                            if (innerFile.getName().endsWith(".docx")) {
                                if (camera.equals("F")) {
                                    info = readWordFile(innerFile).split("自由曲面相机")[1];
                                    fileData.setSensor("自由曲面相机");
                                    fileData.setSpatialResolution(17);
                                } else if (camera.equals("M")) {
                                    fileData.setSensor("中红外相机");
                                    fileData.setSpatialResolution(200);
                                    info = readWordFile(innerFile).split("自由曲面相机")[0];
                                } else throw new BusinessException(ErrorCode.PARAMS_ERROR, "传感器数据异常");
                                Date date = getDate(info, tifName);
                                fileData.setFileName(tifName);
                                fileData.setGetTime(date);
                                fileData.setCreateUser(userId);

                                switch (grade) {
                                    case "L0":
                                        fileData.setGrade("原始影像");
                                        break;
                                    case "L1":
                                        fileData.setGrade("一级辐射校正产品");
                                        break;
                                    case "L2":
                                        fileData.setGrade("一级几何校正产品");
                                        break;
                                    default:
                                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "影像等级数据异常");
                                }
                                fileData.setRadiationResolution(16);
                                fileData.setProjection("UTM");

                                for (String s : txt) {
                                    String[] infos = s.split("；");
                                    if (infos.length < 5) {
                                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "txt文件数据异常");
                                    }
                                    if (infos[0].equals(tifName) && infos[1].equals(camera)) {
                                        String lng = infos[2].replaceAll("[^\\d-.]", "");
                                        Double minLng = Math.min(Double.parseDouble(lng.split("-")[0]), Double.parseDouble(lng.split("-")[1]));
                                        Double maxLng = Math.max(Double.parseDouble(lng.split("-")[0]), Double.parseDouble(lng.split("-")[1]));
                                        fileData.setUpLongitude(maxLng);
                                        fileData.setDownLongitude(minLng);
                                        String lat = infos[3].replaceAll("[^\\d-.]", "");
                                        Double minLat = Math.min(Double.parseDouble(lat.split("-")[0]), Double.parseDouble(lat.split("-")[1]));
                                        Double maxLat = Math.max(Double.parseDouble(lat.split("-")[0]), Double.parseDouble(lat.split("-")[1]));
                                        fileData.setLeftLatitude(minLat);
                                        fileData.setRightLatitude(maxLat);
                                        fileData.setCloudCover(Integer.parseInt(infos[4].replaceAll("\\D", "")));
                                        break;
                                    }
                                }
                                if (index == 1) {
                                    upOne(fileData, tifFile, userId, tifName);
                                    break;
                                } else {
                                    index = 1;
                                }
                            }
                        }
                        fileDataList.add(fileData);
                    }
                }
            }
            return fileDataList;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "解析文件异常");
        }
    }

    public void upOne(FileData fileData, File innerFile, Long userId, String fileName) {
        String innerName = innerFile.getName();
        if (innerName.endsWith("tif") || innerName.endsWith("tiff") || innerName.endsWith("TIF") || innerName.endsWith("TIFF")) {
            try {
                InputStream inputStream = Files.newInputStream(innerFile.toPath());
                InputStream byteArrayInputStream;
                try {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buffer)) > -1) {
                        byteArrayOutputStream.write(buffer, 0, len);
                    }
                    byteArrayOutputStream.flush();
                    byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                } catch (Exception e) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
                fileData.setJpgUrl(TifToJpg.getJpgUrl(byteArrayInputStream));
                if (!save(fileData)) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
                String path = fileData.getId() + "_" + userId + "_" + fileData.getFileName() + "_" + fileName + ".tif";
                try {
                    fileData.setUrl(getUrl(inputStream, path));
                } catch (Exception e) {
                    removeById(fileData.getId());
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
                }
                if (!updateById(fileData)) {
                    delFile(path);
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
            } catch (IOException e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "解析tif文件异常");
            }
        }
    }

    @Override
    public void delFileDataList(List<FileData> fileDataList) {
        fileDataList.forEach(i -> {
            if (getById(i.getId()) != null) {
                removeById(i.getId());
            }
        });
    }

    @Override
    public QueryWrapper<FileData> getQueryWrapper(FileDataQueryRequest fileDataQueryRequest) {
        QueryWrapper<FileData> queryWrapper = new QueryWrapper<>();
        if (fileDataQueryRequest == null) {
            return queryWrapper;
        }

        Double upLongitude = fileDataQueryRequest.getUpLongitude();
        Double downLongitude = fileDataQueryRequest.getDownLongitude();
        Double leftLatitude = fileDataQueryRequest.getLeftLatitude();
        Double rightLatitude = fileDataQueryRequest.getRightLatitude();
        if (!ObjectUtils.allNull(upLongitude, downLongitude, leftLatitude, rightLatitude)) {
            if (ObjectUtils.anyNull(upLongitude, downLongitude, leftLatitude, rightLatitude)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入正确完整的经纬度");
            }
            double up = Math.max(upLongitude, downLongitude);
            double down = Math.min(upLongitude, downLongitude);
            double left = Math.min(leftLatitude, rightLatitude);
            double right = Math.max(leftLatitude, rightLatitude);
            queryWrapper.ge("upLongitude", up);
            queryWrapper.le("downLongitude", down);
            queryWrapper.ge("rightLatitude", right);
            queryWrapper.le("leftLatitude", left);
        }

        Long id = fileDataQueryRequest.getId();
        String fileName = fileDataQueryRequest.getFileName();
        String grade = fileDataQueryRequest.getGrade();
        Integer spatialResolution = fileDataQueryRequest.getSpatialResolution();
        Integer radiationResolution = fileDataQueryRequest.getRadiationResolution();
        String sensor = fileDataQueryRequest.getSensor();
        String projection = fileDataQueryRequest.getProjection();
        String coordinate = fileDataQueryRequest.getCoordinate();
        Integer cloudCover = fileDataQueryRequest.getCloudCover();
        Date leftTime = fileDataQueryRequest.getLeftTime();
        Date rightTime = fileDataQueryRequest.getRightTime();
        String sortField = fileDataQueryRequest.getSortField();
        String sortOrder = fileDataQueryRequest.getSortOrder();
        Integer fileDataState = fileDataQueryRequest.getFileDataState();
        Integer createUserId = fileDataQueryRequest.getCreateUserId();
        
        queryWrapper.like(StringUtils.isNotBlank(fileName), "fileName", fileName);
        queryWrapper.eq(id != null && id != 0, "id", id);
//        queryWrapper.eq("fileDataState", 0);
        queryWrapper.like(StringUtils.isNotBlank(grade), "grade", grade);
        queryWrapper.like(StringUtils.isNotBlank(sensor), "sensor", sensor);
        queryWrapper.like(StringUtils.isNotBlank(projection), "projection", projection);
        queryWrapper.like(StringUtils.isNotBlank(coordinate), "coordinate", coordinate);
        queryWrapper.like(ObjectUtils.isNotEmpty(spatialResolution) && !spatialResolution.equals(0), "spatialResolution", spatialResolution);
        queryWrapper.like(ObjectUtils.isNotEmpty(radiationResolution) && !radiationResolution.equals(0), "radiationResolution", radiationResolution);
        queryWrapper.le(ObjectUtils.isNotEmpty(cloudCover) && !cloudCover.equals(0), "cloudCover", cloudCover);
        queryWrapper.ge(ObjectUtils.isNotEmpty(leftTime), "getTime", leftTime);
        queryWrapper.le(ObjectUtils.isNotEmpty(rightTime), "getTime", rightTime);
//        queryWrapper.between(!ObjectUtils.anyNull(leftTime, rightTime), "getTime", leftTime, rightTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(fileDataState), "fileDataState", fileDataState);
        queryWrapper.eq(ObjectUtils.isNotEmpty(createUserId), "createUser", createUserId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public Page<FileDataVO> getFileDataPageVo(Page<FileData> fileDataPage) {
        List<FileData> fileDataList = fileDataPage.getRecords();
        Page<FileDataVO> fileDataVOPage = new Page<>(fileDataPage.getCurrent(), fileDataPage.getSize(), fileDataPage.getTotal());
        if (CollectionUtils.isEmpty(fileDataList)) {
            return fileDataVOPage;
        }
        List<FileDataVO> fileDataVOList = fileDataList.stream().map(this::getFileDataVO).collect(Collectors.toList());
        fileDataVOPage.setRecords(fileDataVOList);
        return fileDataVOPage;
    }

    @Override
    @Transactional
    public Boolean audit(AuditAddRequest auditAddRequest, HttpServletRequest request) {
        Long fileDataId = auditAddRequest.getFileDataId();
        String content = auditAddRequest.getContent();
        Boolean pass = auditAddRequest.getPass();
        FileData fileData = this.getById(fileDataId);
        if (fileData == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (!userService.isRootAdmin(loginUser) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        QueryWrapper<Audit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fileDataId", fileDataId);
        Audit audit = auditService.getOne(queryWrapper);
        if (audit == null) {
            audit = new Audit();
        }
        if (audit.getUserId() != null && !audit.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "该数据已有管理员审核了");
        }
        audit.setFileDataId(fileDataId);
        audit.setUserId(loginUser.getId());
        if (pass) {
            audit.setAuditRes(0);
            audit.setContent("审核通过");
            fileData.setFileDataState(0);
        } else {
            if (content.isEmpty() || content.equals("undefined")) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入原因");
            }
            audit.setContent("您的申请未通过，原因是：" + content);
            audit.setAuditRes(-1);
            fileData.setFileDataState(-1);
            emailUtils.sendEmail(userService.getById(fileData.getCreateUser()).getUserEmail(), content);
        }
        if (!this.updateById(fileData) || !auditService.saveOrUpdate(audit)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public Boolean isOwn(Long userId, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return userService.isAdmin(loginUser) || userService.isRootAdmin(loginUser) || loginUser.getId().equals(userId);
    }

    @Override
    public Page<FileData> getPage(Page<Object> page, QueryWrapper<FileData> queryWrapper) {
        List<FileData> list = this.list(queryWrapper);
        List<FileData> newList = list.stream().map((fileData) -> {
            String jpgUrl = fileData.getJpgUrl();
            if (StringUtils.isAnyBlank(jpgUrl)) {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(fileData.getUrl()).build();
                    Response response = okHttpClient.newCall(request).execute();
                    byte[] imageData = response.body() != null ? response.body().bytes() : new byte[0];
                    InputStream inputStream = new ByteArrayInputStream(imageData);
                    fileData.setJpgUrl(TifToJpg.getJpgUrl(inputStream));
                    updateById(fileData);
                    inputStream.close();
                    response.close();
                    return fileData;
                } catch (Exception e) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统异常，解析影像失败");
                }
            }
            return fileData;
        }).collect(Collectors.toList());
        Page<FileData> fileDataPage = new Page<>(page.getCurrent(), page.getSize(), newList.size());
        fileDataPage.setRecords(newList);
        return fileDataPage;
    }

    @Override
    public FileDataCountVO countAll() {
        FileDataCountVO fileDataCountVO = new FileDataCountVO();
        long total = count();
        if (total == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有数据可统计");
        }
        fileDataCountVO.setTotal(total);
        long L0Count = countOne("grade", "原始影像");
        fileDataCountVO.setL0(L0Count);
        long L1Count = countOne("grade", "一级辐射校正产品");
        fileDataCountVO.setL1(L1Count);
        long L2Count = countOne("grade", "一级几何校正产品");
        fileDataCountVO.setL2(L2Count);
        Long ZY = countOne("sensor", "自由曲面相机");
        fileDataCountVO.setSensorZYQM(ZY);
        Long ZHW = countOne("sensor", "中红外相机");
        fileDataCountVO.setSensorZHW(ZHW);
        FileData downLongitude = max_minOne("downLongitude", "min");
        fileDataCountVO.setMinLongitude(downLongitude.getDownLongitude());
        FileData upLongitude = max_minOne("upLongitude", "max");
        fileDataCountVO.setMaxLongitude(upLongitude.getUpLongitude());
        FileData leftLatitude = max_minOne("leftLatitude", "min");
        fileDataCountVO.setMinLatitude(leftLatitude.getLeftLatitude());
        FileData rightLatitude = max_minOne("rightLatitude", "max");
        fileDataCountVO.setMaxLatitude(rightLatitude.getRightLatitude());
        FileData maxTime = max_minOne("getTime", "max");
        fileDataCountVO.setMinTime(maxTime.getGetTime());
        FileData minTime = max_minOne("getTime", "min");
        fileDataCountVO.setMaxTime(minTime.getGetTime());
        FileData maxCloudCover = max_minOne("cloudCover", "max");
        fileDataCountVO.setMaxCloudCover(maxCloudCover.getCloudCover());
        fileDataCountVO.setMinTime(maxTime.getGetTime());
        FileData minCloudCover = max_minOne("cloudCover", "min");
        fileDataCountVO.setMinCloudCover(minCloudCover.getCloudCover());
        return fileDataCountVO;
    }

    @Override
    public Long countOne(String col, String str) {
        QueryWrapper<FileData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(col, str);
        return count(queryWrapper);
    }

    @Override
    public FileData max_minOne(String col, String ai) {
        QueryWrapper<FileData> queryWrapper = new QueryWrapper<>();
        if (ai.equals("max"))
            queryWrapper.select("max(" + col + ") as " + col);
        else queryWrapper.select("min(" + col + ") as " + col);
        return getOne(queryWrapper);
    }

    @Override
    public List<FileDataVO> pointSer(Map<String, String> map) {
        List<FileDataVO> fileDataVOList = new ArrayList<>();
        for (String s : map.keySet()) {
            if (StringUtils.isAnyBlank(s))
                continue;
            double lng = Double.parseDouble(s);
            double lat = Double.parseDouble(map.get(s));
            QueryWrapper<FileData> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("upLongitude", lng);
            queryWrapper.le("downLongitude", lng);
            queryWrapper.ge("rightLatitude", lat);
            queryWrapper.le("leftLatitude", lat);
            List<FileData> fileDataList = list(queryWrapper);
            if (fileDataList == null || fileDataList.isEmpty())
                continue;
            fileDataVOList.addAll(getFileDataVOList(fileDataList));
        }
        fileDataVOList = fileDataVOList.stream().distinct().collect(Collectors.toList());
        return fileDataVOList;
    }

    @Override
    public List<FileDataVO> rectSer(Map<String, String> map) {
        List<FileDataVO> fileDataVOList = new ArrayList<>();
        for (String s : map.keySet()) {
            if (StringUtils.isAnyBlank(s))
                continue;
            String minLng = s.split("_")[0];
            String maxLng = s.split("_")[1];
            String minLat = map.get(s).split("_")[0];
            String maxLat = map.get(s).split("_")[1];
            QueryWrapper<FileData> queryWrapper = new QueryWrapper<>();
            queryWrapper.le("upLongitude", maxLng)
                    .ge("downLongitude", minLng)
                    .le("rightLatitude", maxLat)
                    .ge("leftLatitude", minLat);
            List<FileData> inner = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(inner));

            queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("upLongitude", maxLng)
                    .le("downLongitude", minLng)
                    .ge("rightLatitude", maxLat)
                    .le("leftLatitude", minLat);
            List<FileData> incl = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(incl));

            queryWrapper = new QueryWrapper<>();
            queryWrapper.between("upLongitude", minLng, maxLng)
                    .and(i -> i.between("rightLatitude", minLat, maxLat)
                            .or()
                            .between("leftLatitude", minLat, maxLat));
            List<FileData> maxLngBetween = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(maxLngBetween));

            queryWrapper = new QueryWrapper<>();
            queryWrapper.between("downLongitude", minLng, maxLng)
                    .and(i -> i.between("rightLatitude", minLat, maxLat)
                            .or()
                            .between("leftLatitude", minLat, maxLat));
            List<FileData> minLngBetween = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(minLngBetween));

            queryWrapper = new QueryWrapper<>();
            queryWrapper.between("rightLatitude", minLat, maxLat)
                    .and(i -> i.between("upLongitude", minLng, maxLng)
                            .or()
                            .between("downLongitude", minLng, maxLng));
            List<FileData> maxLatBetween = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(maxLatBetween));

            queryWrapper = new QueryWrapper<>();
            queryWrapper.between("leftLatitude", minLat, maxLat)
                    .and(i -> i.between("upLongitude", minLng, maxLng)
                            .or()
                            .between("downLongitude", minLng, maxLng));
            List<FileData> minLatBetween = list(queryWrapper);
            fileDataVOList.addAll(getFileDataVOList(minLatBetween));

        }
        fileDataVOList = fileDataVOList.stream().distinct().collect(Collectors.toList());
        return fileDataVOList;
    }

    @Override
    public Page<FileDataVO> AllSer(long current, long pageSize, Map<String, String> map) {
        List<FileDataVO> fileDataVOList = new ArrayList<>();
        Map<String, String> pointMap = new HashMap<>();
        Map<String, String> rectMap = new HashMap<>();
        for (String s : map.keySet()) {
            if (StringUtils.isAnyBlank(s))
                continue;
            if (s.contains("_")) {
                rectMap.put(s, map.get(s));
                continue;
            }
            pointMap.put(s, map.get(s));
        }
        List<FileDataVO> pointSerList = pointSer(pointMap);
        List<FileDataVO> rectSerList = rectSer(rectMap);
        fileDataVOList.addAll(pointSerList);
        fileDataVOList.addAll(rectSerList);
        fileDataVOList = fileDataVOList.stream().distinct().collect(Collectors.toList());
        Page<FileDataVO> fileDataVOPage = new Page<>(current, pageSize, fileDataVOList.size());
        fileDataVOPage.setRecords(fileDataVOList);
        return fileDataVOPage;
    }

    @Override
    public String getUrl(InputStream fileInputStream, String fileName) {
        return OssClient.uploadFileToOSS(fileInputStream, fileName);
    }

    @Override
    public void delFile(String fileName) {
        OssClient.delFile(fileName);
    }

}




